Page({
  data: {
    pageShow:false,  //扫码返回或者能再次扫码时使用
    choiceShow: false, //扫码成功后使用
    bindShow: false, //验证绑定结果时使用
    alertShow:false, //登录页弹出框使用,
    iWillFan:false, // 我要反占座
    iFanSuccess:false, // 反占座成功
    iComeResult:false, // 我回来了后的结果公示
    iRecive:false, // 接收离座提醒
    iReciveNow:false, //正在接收离座提醒
    iWillComeNow:false, // 在离座提醒页的点击
    iTakePic:false, // 拍照留存
    iWillCome: false,//我回来了
    icome_name:null, //我回来了那个人的名字
    icome_alerm:'00:00', // 我回来了后计时器停止的时间
    iBell:false, // 计时器
    iBell_alerm:'00:00', // 计时器时间,
    t:null, // 计数器
    t1:null, // 请求runSeat计数器
    iComeDone:0,//用来记录是否清除定时器
    userInfo: null,
    userData:null,
    msg:'我要反占座',
    isFan:0,  //是否是正在反占座
    isScan:0, //是否扫码成功，0为未成功，1为成功
    time:60,
    isShow:true,
    seat_num:0, //座位号
    stuid:null, //学号
    password:null, //密码
    openid:null,
    userId:null,
    iAlermDone:0,    
    rules: [],
    message:'',
    seat_num_id:'', //当前操作的记录的ID
    lbsShow:false,
    lbs_message:[],
    latitude:'',
    longitude:''
  },
  onLoad: function (options) {
    console.log(options)
    // wx.redirectTo({
    //   url: '/bookgo/fan/prepare/prepare',
    // })
    console.log(options);   
    this.login();
    // 获取message
    this.get_message();
    
  },
  login: function () {
    console.log('logining..........');
    const that = this;
    
    //调用登录接口
    wx.login({
      success: function (e) {
        var openid = wx.getStorageSync('openid');
        if (!openid) {
          wx.request({
            url: 'https://2016.bookgo.com.cn/wxapp/index/login',
            data: {
              code: e.code
            },
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {
              console.log('============反占座 res===========');
              console.log(res);
              wx.setStorageSync('openid', res.data.openid)
              that.checkUser(res.data.openid);
              
            },
            fail: function (res) {
              console.log(res)
            }
          })
        } else {
          that.checkUser(openid);
        }
        console.log('wxlogin successd........');
      }
    });
  },
  checkUser: function (openid) {
    const that = this;

    that.setData({
      openid: openid,
      userInfo: wx.getStorageSync('userInfo')
    });
    // 判断是否有登录状态
    var user = wx.getStorageSync('user');
    console.log(user);
    if (!user) {
      console.log('开始获取用户信息');
      wx.request({
        url: 'https://2016.bookgo.com.cn/wxapp/index/check_user',
        data: {
          openid: openid,
          aid:3
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
          switch (res.data.code) {
            case 101:
              wx.setStorageSync('user', res.data.user);
              wx.setStorageSync('user_done', 'yes');     
              that.login_success(res.data.user);

              break;
            case 102:
              wx.setStorageSync('user', res.data.user);
              wx.setStorageSync('user_done', 'no');
              that.setData({
                userData: res.data.user
              });
              // var t_choice = wx.getStorageSync('t_choice');
              // if(typeof(t_choice) == 'undefined'){
              //   that.setData({
              //     t_choice: true
              //   });
              // }else{
              //   that.setData({
              //     t_choice: t_choice
              //   });
              // }
              
              that.pageControl('loginShow');
              break;
            case 104:
              console.log('**去登录**');
              wx.setStorageSync('user_done', 'none');
              // var t_choice = wx.getStorageSync('t_choice');
              // if (typeof (t_choice) == 'undefined') {
              //   that.setData({
              //     t_choice: true
              //   });
              // } else {
              //   that.setData({
              //     t_choice: t_choice
              //   });
              // }
              that.pageControl('loginShow');        
              break;
          }
        },
        fail: function () {
          that.checkUser(openid);
        }
      })
    }else{
      that.login_success(user);
    }
  },
  login_success:function(user){
    this.setData({
      userData: user,
      userId: user.id
    });
    wx.setStorageSync('usreId', user.id);
    this.todo();
  },
  check_data: function () {
    // 判断是否已经有了openid，若没有则等有了才进行相关操作
    const that = this;
    console.log('***检查数据****')
    wx.getStorage({
      key: 'openid',
      success: function(res) {
        that.setData({
          openid: res.data
        });
      },
    });
    wx.getStorage({
      key: 'user',
      success: function (res) {
        that.setData({
          userData: res.data
        });
      },
    });
    wx.getStorage({
      key: 'userInfo',
      success: function (res) {
        that.setData({
          userInfo: res.data
        });
      },
    });
    wx.getStorage({
      key: 'user_done',
      success: function (res) {
        console.log(res)
        var user_done = res.data;
        if (user_done != 'none') {
          that.setData({
            userId: user.id
          });
          wx.setStorageSync('usreId', user.id);
        }
        that.checkUser(user_done);
      },
    });
    // var openid = wx.getStorageSync('openid');
    // var user = wx.getStorageSync('user');
    // var user_done = wx.getStorageSync('user_done');

    // this.setData({
    //   userInfo: wx.getStorageSync('userInfo'),
    //   userData: wx.getStorageSync('user'),
    //   openid: openid
    // }); 
    // console.log('这是check_data')
    // if (openid && user) {
    //   console.log('check_data done');
    //   if(user_done != 'none'){
    //     this.setData({
    //       userId: user.id
    //     });
    //     wx.setStorageSync('usreId', user.id);
    //   }
    //   checkUser(user_done);
    // } else { 
    //   setTimeout(this.check_data,30);
    // }
  },
  get_message:function(){
    const that = this;
    var _t = (new Date()).getTime();
    wx.request({
      url: 'https://2016.bookgo.com.cn/wxapp/index/get_message?time=_t',
      data: {
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data)
        that.setData({
          message: res.data.message
        });
      },
      fail: function (res) {
        
      },
      complete: function () {

      }
    })
  },
  get_lbs_message: function () {
    const that = this;
    var _t = (new Date()).getTime();
    if (that.data.lbs_message.length == 0){
      wx.request({
        url: 'https://2016.bookgo.com.cn/wxapp/index/get_lbs_message?time=_t',
        data: {
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log('************lbs_message*************');
          console.log(res.data)
          that.setData({
            lbs_message: res.data
          });
        },
        fail: function (res) {

        },
        complete: function () {

        }
      });
    }
    
  },
  scanCode:function(){
    // 开始扫码
    const that = this;

    var bell_time = that.data.iBell_alerm.substr(0, 2) + '' + that.data.iBell_alerm.substr(3, 2);
  // 如果计时器在计时，则不允许使用扫描操作
    if (bell_time != '0000' && (bell_time - 2000) < 2){
      // wx.showModal({
      //   title: '提示',
      //   showCancel: false,
      //   content: '反占座计时中不允许使用扫码操作',
      //   success: function (res) {
      //     if (res.confirm) {
      //       console.log('用户点击确定')
      //     }
      //   }
      // });
      // return false;
    }
    if (that.rest_time()) return false;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        // res.result扫码的内容
        var code = that.decode(res.result);
        var zuowei = code.substr(-4); 
        var pattern = code.substr(0,12);
        console.log('############')
        console.log(pattern);
        if (pattern != 'cug-bookgoal'){
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '不是有效的二维码',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          });
          return false;
        }
        console.log(that.data)
        that.titleControl('iWillFan');
        that.setData({
          isScan:1,
          seat_num:zuowei,
          iRecive: true, // 接收离座提醒
          iWillCome: true,//我回来了
          iTakePic:false,
          iWillComeNow:false,
        });     
      },
      fail:function(){

      },
      complete:()=>{
        switch(that.data.isScan){
          case 1:
            that.pageControl('choiceShow');
            break;
        }
      }
    })   
  },
  scanCodeConfirm:function(status){  
    console.log(status)
    const that = this;
    wx.showModal({
      title: '提示',
      content: '您确定要离开本界面吗？',
      success: function (res) {
        if (res.confirm) {
          if (that.data.iReciveNow){
            that.quit(that.data.userId, that.data.seat_num, 2);
          }else{
            that.quit(that.data.userId, that.data.seat_num, 1);
          }
          
          // 这里是确定重新进行反占座
          that.refresh()
          that.setData({
            iComeDone:1
          });
        } else if (res.cancel) {
          
        }
      }
    });
  },
  quit:function(userId,seat_num,status){
    const that = this;
    var _t = (new Date()).getTime();
    wx.request({
      url: 'https://2016.bookgo.com.cn/wxapp/index/iquit?time=_t',
      data: {
        userId: that.data.userId,
        seat_num: that.data.seat_num,
        aid: 3,
        status:status
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data)

      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '请求错误，请重试',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        });
      },
      complete: function () {

      }
    })
  },
  quitRevice:function(){

    const that = this;
    wx.showModal({
      title: '提示',
      content: '您确定要取消接收离座提醒吗？',
      success: function (res) {
        if (res.confirm) {
          that.quit(that.data.userId, that.data.seat_num, 2);
          // 这里是确定重新进行反占座
          that.refresh();
          that.setData({
            iComeDone: 1
          });
          // 回到原始装态
          that.refresh();
        } else if (res.cancel) {

        }
      }
    });
  },
  scanCodeConfirmScan: function () {
    const that = this;
    wx.showModal({
      title: '提示',
      content: '您确定要离开本界面吗？',
      success: function (res) {
        if (res.confirm) {
          if (that.data.iReciveNow) {
            that.quit(that.data.userId, that.data.seat_num, 2);
          } else {
            that.quit(that.data.userId, that.data.seat_num, 1);
          }
          // 这里是确定重新进行反占座
          that.setData({
            iComeDone: 1
          });
          that.scanCode();
        } else if (res.cancel) {

        }
      }
    });
  },
  iFan:function(formId){
    // 进行反占座操作
    const that = this;
    if (that.rest_time()) return false;
    var _t = (new Date()).getTime();
    that.setData({
      userInfo: wx.getStorageSync('userInfo'),
      userData: wx.getStorageSync('user'),
      userId: (wx.getStorageSync('user')).id,
      iComeDone:0
    });
    wx.request({
      url: 'https://2016.bookgo.com.cn/wxapp/index/iFan?time=_t',
      data: {
        ifan_id: that.data.userId,
        seat_num:that.data.seat_num,
        aid:3,
        ifan_time: Math.round(_t / 1000),
        form_id: formId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log('************************iFan*******************')
        console.log(res.data)
        // return;
        switch (res.data.code) {
          case 101:
            that.setData({
              iAlermDone: 0
            });
            // 反占座成功后需要获取这条记录id并进行定时操作
            clearTimeout(that.data.t);
            clearTimeout(that.data.t1);
            that.runSeat(res.data.data);
            that.status_iFan();
            break;
          case 102:
            console.log(res.data.data);            
            var has = res.data.data;
            wx.showModal({
              title: '提示',
              content: '您在' + has.zhan_time + '已经对' + has.seat_num + '号座位进行了反占座操作，确定要释放上个座位并反占座' + that.data.seat_num + '号座位吗？',
              success: function (res) {
                if (res.confirm) {
                  // 这里是确定重新进行反占座
                  that.mustFan(has.id)
                } else if (res.cancel) {
                  that.setData({
                    iWillFan: false,
                    iRecive: false,
                    iTakePic: true,
                    iWillCome: false
                  });
                }
              }
            });
            
            break;
          case 103:
            console.log(res.data.data);
            that.runSeat(res.data.data.id);
            that.status_iFan();
            var has = res.data.data;
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '您在' + has.zhan_time + '已经对' + that.data.seat_num + '号座位进行了反占座操作！',
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
            break;
          case 104:
            // 服务器错误
            wx.showModal({
              title: '提示',
              content: res.data.data,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
            break;
          default:
            console.log(res.data)
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '请求错误，请重试',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        });
      },
      complete: function () {
        //将下面的我回来了消除
        that.setData({
          iWillCome:false
        });
        console.log('request complete')
      }
    })
  },
  iFanNow:function(e){
    var formId = e.detail.formId;
    // 这是调起扫码来判断结果的流程
    const that = this;
    var _t = (new Date()).getTime();
    if (that.rest_time()) return false;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        // res.result扫码的内容
        var code = that.decode(res.result);
        var zuowei = code.substr(-4);
        var pattern = code.substr(0, 12);
        console.log('############')
        console.log(pattern);
        if (pattern != 'cug-bookgoal') {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '不是有效的二维码',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          });
          return false;
        }
        that.setData({
          isScan: 1,
          seat_num: zuowei,
        });
        that.pageControl('choiceShow')
        that.iFan(formId);

      },
      fail: function () {

      },
      complete: () => {

      }
    }); 
  },
  iTakePic:function(){
    // 照相
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePaths[0],
          success(res) {
            console.log(res)
          }
        })
      }
    })
  },
  mustFan:function(id){
    // 放弃以前的座位强制反占座当前座位
    const that = this;
    that.setData({
      userInfo: wx.getStorageSync('userInfo'),
      userData: wx.getStorageSync('user'),
      userId: (wx.getStorageSync('user')).id,
      iComeDone:0
    });
    var _t = (new Date()).getTime();
    wx.request({
      url: 'https://2016.bookgo.com.cn/wxapp/index/mustFan?time=_t',
      data: {
        id:id,
        ifan_id: that.data.userId,
        seat_num: that.data.seat_num,
        aid: 3,
        ifan_time: Math.round(_t / 1000)
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data)
        switch (res.data.code) {
          case 101:
            console.log('反占座成功后需要获取这条记录id并进行定时操作')
            // 反占座成功后需要获取这条记录id并进行定时操作
            that.setData({
              iAlermDone: 0
            });
            clearTimeout(that.data.t);
            clearTimeout(that.data.t1);
            that.runSeat(res.data.data);
            that.status_iFan();
            that.pageControl('choiceShow');
            console.log(that.data)
            break;
          case 104:
            // 服务器错误
            wx.showModal({
              title: '提示',
              content: res.data.data,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
            break;
          default:
            console.log(res.data)
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '请求错误，请重试',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            }
          }
        });
      },
      complete: function () {
        console.log('request complete')
      }
    })
  },
  runSeat:function(id){
    // 将反占座id发送并监控是否有更新消息
    this.setData({
      seat_num_id:id
    });
    const that = this;
    var _t = (new Date()).getTime();
    if(that.data.iComeDone == 1){
      clearTimeout(this.data.t);
      clearTimeout(this.data.t1);
      return false;
    }
    wx.request({
      url: 'https://2016.bookgo.com.cn/wxapp/index/runSeat?time=_t',
      data: {
        id: id,
        who:that.data.userId,
        aid:3
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log('$$$$$$$$$$$$$$')
        console.log(res.data)
        switch (res.data.code) {
          case 100:
            // 继续请求
            if(that.data.iAlermDone == 0){
              that.runAlerm(res.data.data.ifan_time);
              that.setData({
                  iAlermDone : 1
              });
            }
            var t = setTimeout(function(){
              that.runSeat(id)
            }, 5000);
            that.setData({
              t1:t
            })
            break;
          case 101:
            // 反占座成功
            clearTimeout(that.data.t);
            clearTimeout(that.data.t1);
            that.titleControl('iFanSuccess');
            that.setData({
              iComeResult: false,
              iBell: false,
              iRecive:true,
              iTakePic:false,
              stop_time: res.data.data.time
            });
            break;
          case 110:
            that.pageControl('pageShow');
            break;
          case 102:
            // A回来了
            that.iComeDone(res.data.data.ifan_time, res.data.data.name, 0, res.data.data.icome_time);
            that.setData({
              stop_time: res.data.data.time
            });
            
            break;
          case 104:
            // 服务器错误
            wx.showModal({
              title: '提示',
              content: res.data.data,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
            break;
          default:
            console.log(res.data)
        }
      },
      fail: function (res) {
        var t = setTimeout(function () {
          that.runSeat(id)
        }, 5000);
        that.setData({
          t1: t
        })
      },
      complete: function () {
        
      }
    });
  },
  iWillComeNow:function(){
    // 这是调起扫码来判断结果的流程
    const that = this;
    var _t = (new Date()).getTime();
    if (that.rest_time()) return false;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        // res.result扫码的内容
        var code = that.decode(res.result);
        var zuowei = code.substr(-4);
        var pattern = code.substr(0, 12);
        console.log('############')
        console.log(pattern);
        if (pattern != 'cug-bookgoal') {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '不是有效的二维码',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              }
            }
          });
          return false;
        }
        that.setData({
          isScan: 1,
          seat_num: zuowei,
        }); 
        that.iWillCome();

      },
      fail: function () {

      },
      complete: () => {

      }
    }); 
    
  },
  iWillReciveNow:function(){
    const that = this;
    // 这是调起扫码来判断结果的流程
    if (that.rest_time()) return false;
    // 获取经纬度
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });

        var _t = (new Date()).getTime();
        
        wx.scanCode({
          onlyFromCamera: true,
          success: (res) => {
            // res.result扫码的内容
            var code = that.decode(res.result);
            var zuowei = code.substr(-4);
            var pattern = code.substr(0, 12);
            console.log('############')
            console.log(pattern);
            if (pattern != 'cug-bookgoal') {
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: '不是有效的二维码',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                  }
                }
              });
              return false;
            }
            that.setData({
              isScan: 1,
              seat_num: zuowei,
            });
            that.iRecive();
          },
          fail: function () {

          },
          complete: () => {

          }
        }); 
      },
      fail: function (res) {
        console.log(res);
        that.get_lbs_message();
        that.setData({
          lbsShow: true
        });
        return false;
      }
    });
 
  },
  iComeDone(time,name,fan = 0,icome_time = 0){
    /* time  反占座的时间
       name  座位被判给谁
       fan   是否反占座成功了
       icome_time 我回来了的时间
    */
    const that = this;
    clearTimeout(that.data.t);
    clearTimeout(that.data.t1);
    // 如果是『我回来了』，则当下时间应取『我回来了』的时间
    if(icome_time == 0){
      var date = new Date();
      var now = Math.round(date.getTime() / 1000);
      
    }else{
      var now = icome_time;
    }
    var cha = now - time;
    console.log(cha)
    var minute = (parseInt((cha / 60)) < 10) ? '0' + parseInt((cha / 60)) : parseInt((cha / 60));
    var second = ((cha % 60) < 10) ? '0' + (cha % 60) : (cha % 60);
    // 如果是反占座成功，则显示20，否则则显示当前计时器时间
    var alerm = (fan == 0) ? (minute + ':' + second) : '20:00'
    var irecive = (fan == 0) ? false : true;
    that.titleControl('iComeResult');
    that.setData({
      icome_name: name,
      
      icome_alerm: alerm,
      iBell: false,
      iWillCome:false,
      iTakePic:false,
      iWillComeNow:false,
      // iRecive: irecive,
      iComeDone:1
    });
    
  },
  runAlerm:function(time){
    // 计时器
    if(this.data.iComeDone == 1){
      clearTimeout(this.data.t);
      clearTimeout(this.data.t1);
      return false;
    }
    // clearTimeout(this.data.t);
    var date = new Date();
    var now = Math.round(date.getTime() / 1000);
    var cha = now - time;
    console.log(cha)
    var minute = (parseInt((cha / 60)) < 10) ? '0' + parseInt((cha / 60)) : parseInt((cha / 60));
    var second = ((cha % 60) < 10) ? '0' + (cha % 60) : (cha % 60);
    this.setData({
      iBell_alerm: minute + ':' + second
    })
    const that = this;
    var t = setTimeout(function(){
      that.runAlerm(time);
    },1000);
    this.setData({
      t: t
    })
  },
  closeLbsAlert:function(){
    this.setData({
      lbsShow:false
    });
  },
  iRecive:function(){
    // 接收离座提醒
    const that = this;
    that.setData({
      userInfo: wx.getStorageSync('userInfo'),
      userData: wx.getStorageSync('user'),
      userId: (wx.getStorageSync('user')).id
    });

    // 获取经纬度
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        var _t = (new Date()).getTime();
        wx.request({
          url: 'https://2016.bookgo.com.cn/wxapp/index/iRecive?time=_t',
          data: {
            seat_num: that.data.seat_num,
            who: that.data.userId,
            aid: 3,
            latitude: res.latitude,
            longitude: res.longitude
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            // return;
            switch (res.data.code) {
              case 101:
                // 设置成功
                wx.showToast({
                  title: '设置成功',
                  icon: 'success',
                  duration: 2000
                });
                that.setData({
                  seat_num_id: res.data.data
                });
                that.status_iRecive();
                break;
              case 102:
                // 设置成功
                wx.showToast({
                  title: '设置成功',
                  icon: 'success',
                  duration: 2000
                })
                that.status_iRecive();
                break;
              case 104:
                // 服务器错误
                wx.showModal({
                  title: '提示',
                  content: '出现错误，请重试！',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              case 105:
                // 如果已经有一次我回来了且是本人，说明没人对这个座位有反占座权
                wx.showModal({
                  title: '提示',
                  content: '当前座位没有被反占座，无需此操作！',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              case 106:
                // 如果已经有一次我回来了且不是本人，该座位没有人进行反占座操作，所以没有人有这个座位的反占座权
                wx.showModal({
                  title: '提示',
                  content: '当前座位没有被反占座，无需此操作！',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;

              default:
                console.log(res.data)
            }
          },
          fail: function (res) {
            console.log('计时请求出错');
          },
          complete: function () {
            // setTimeout(that.runSeat(id), 30000);
          }
        });
      }, 
      fail:function(res){
        that.get_lbs_message();
        that.setData({
          lbsShow: true
        });
        return false;
      }
    });

    
  },
  iWillCome:function(){
    // 我回来啦，这是正常流程
    const that = this;

    // 获取经纬度
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
        that.setData({
          userInfo: wx.getStorageSync('userInfo'),
          userData: wx.getStorageSync('user'),
          userId: (wx.getStorageSync('user')).id
        });
        var _t = (new Date()).getTime();
        console.log(that.data.seat_num);
        console.log(that.data.userId)
        wx.request({
          url: 'https://2016.bookgo.com.cn/wxapp/index/iWillCome?time=_t',
          data: {
            seat_num: that.data.seat_num,
            who: that.data.userId,
            aid: 3,
            latitude: res.latitude,
            longitude: res.longitude
          },
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            switch (res.data.code) {
              case 101:
                // 我回来了成功
                that.iComeDone(res.data.data.ifan_time, res.data.data.name, 0, res.data.data.icome_time);
                that.setData({
                  stop_time: res.data.data.time,
                  seat_num_id: res.data.data.id
                });
                that.pageControl('choiceShow');
                break;
              case 102:
                // 当前没有人占有这个座位
                wx.showModal({
                  title: '提示',
                  content: res.data.data,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      that.pageControl('pageShow');
                    }
                  }
                });
                break;
              case 103:
                // 座位被反了
                that.iComeDone(res.data.data.ifan_time, res.data.data.name, 1);
                that.setData({
                  stop_time: res.data.data.time,
                  seat_num_id: res.data.data.id
                });
                that.pageControl('choiceShow');
                break;
              case 104:
                // 服务器错误
                wx.showModal({
                  title: '提示',
                  content: res.data.data,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              case 105:
                // 如果已经有一次我回来了且是本人，说明没人对这个座位有反占座权
                wx.showModal({
                  title: '提示',
                  content: '当前座位没有被反占座，无需此操作！',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              case 106:
                // 如果已经有一次我回来了且不是本人，该座位没有人进行反占座操作，所以没有人有这个座位的反占座权
                wx.showModal({
                  title: '提示',
                  content: '当前座位没有被反占座，无需此操作！',
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              case 107:
                // 有人设置了提醒，但是他人来进行我回来了的操作
                wx.showModal({
                  title: '提示',
                  content: res.data.data,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              case 108:
                // 距离超出
                wx.showModal({
                  title: '提示',
                  content: res.data.data,
                  showCancel: false,
                  success: function (res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                    }
                  }
                });
                break;
              default:
                console.log(res.data)
            }
          },
          fail: function (res) {
            console.log('计时请求出错');
          },
          complete: function () {
            // setTimeout(that.runSeat(id), 30000);
          }
        });

       
      },
      fail: function (res) {
        console.log(res);
        that.get_lbs_message();
        that.setData({
          lbsShow: true
        });
        return false;
      }
    });

    
  },
  pageControl:function(page){
    console.log('去登录');
    console.log(page);
    switch(page){
      case 'pageShow':
        this.setData({
          pageShow: true,
          bindShow: false,
          choiceShow: false,
        });
        this.refresh();
        break;
      case 'loginShow':
        wx.setStorageSync('redirect', '/bookgo/fan/ifan/ifan');
        wx.redirectTo({
          url: '/bookgo/login/login'
        });
        // wx.navigateTo({
        //   url: '/bookgo/fan/login/login'
        // });
        break;
      case 'bindShow':
        this.setData({
          pageShow: false,
          bindShow: true,
          choiceShow: false,
        });
        break;
      case 'choiceShow':
        this.setData({
          pageShow: false,
          bindShow: false,
          choiceShow:true,
        });
        break;
      case 'historyShow':
        this.setData({
          pageShow: false,
          bindShow: false,
          choiceShow: false,
        });
        break;
        
      default:
        this.setData({
          pageShow: false,
          bindShow: false,
          choiceShow: false,
        });
    }
  },
  titleControl:function(item){
    switch (item) {
      case 'iWillFan':
        this.setData({
          iWillFan: true,
          iBell: false,
          iFanSuccess: false,
          iComeResult: false,
          iReciveNow:false
        });
        break;
      case 'iBell':
        this.setData({
          iWillFan: false,
          iBell: true,
          iFanSuccess: false,
          iComeResult: false,
          iReciveNow: false
        });
        break;
      case 'iFanSuccess':
        this.setData({
          iWillFan: false,
          iBell: false,
          iFanSuccess: true,
          iComeResult: false,
          iReciveNow: false
        });
        break;
      case 'iComeResult':
        this.setData({
          iWillFan: false,
          iBell: false,
          iFanSuccess: false,
          iComeResult: true,
          iReciveNow: false
        });
        break; 
      case 'iReciveNow':
        this.setData({
          iWillFan: false,
          iBell: false,
          iFanSuccess: false,
          iComeResult: false,
          iReciveNow: true
        });
        break;
      default:
        this.setData({
          iWillFan: true,
          iBell: false,
          iFanSuccess: false,
          iComeResult: false,
          iReciveNow: false
        });
    }
  },
  showAlert:function(){
    const that = this;
    if(that.data.rules.length == 0){
      wx.request({
        url: 'https://2016.bookgo.com.cn/wxapp/index/get_rule',
        data: {},
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data);
          var data = res.data;
          var items = []
          for (var i = 0; i < data.length; i++) {
            var item = {
              text: data[i].text
            };
            items.push(item);
          }
          console.log(items)
          that.setData({
            rules: items
          });
        },
        fail: function (res) {

        },
        complete: function () {

        }
      });
    }
    
    // 弹出框显示
    this.setData({
      alertShow:true
    });
  },
  closeAlert: function () {
    // 弹出框隐藏
    this.setData({
      alertShow: false
    });
  },
  _utf8_decode:function(utftext) {
    var string = "";
    var i = 0;
    var c = 0;
    var c2 = 0;
    var c1 = 0;
    var c3 = 0;
    while(i < utftext.length ) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      } else {
        c2 = utftext.charCodeAt(i + 1);
        c3 = utftext.charCodeAt(i + 2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
  return string;
  },
  decode: function (input) {
    var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
      enc1 = _keyStr.indexOf(input.charAt(i++));
      enc2 = _keyStr.indexOf(input.charAt(i++));
      enc3 = _keyStr.indexOf(input.charAt(i++));
      enc4 = _keyStr.indexOf(input.charAt(i++));
      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;
      output = output + String.fromCharCode(chr1);
      if (enc3 != 64) {
        output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
        output = output + String.fromCharCode(chr3);
      }
    }
    output = this._utf8_decode(output);
    return output;
  },
  goHistory:function(){
    wx.navigateTo({
      url: '/bookgo/fan/history/history'
    })
  },
  refresh:function(){
    this.setData({
      pageShow: true,  //扫码返回或者能再次扫码时使用
      choiceShow: false, //扫码成功后使用
      bindShow: false, //验证绑定结果时使用
      alertShow: false, //登录页弹出框使用,
      iWillFan: false, // 我要反占座
      iFanSuccess: false, // 反占座成功
      iComeResult: false, // 我回来了后的结果公示
      iRecive: false, // 接收离座提醒
      iReciveNow: false, //正在接收离座提醒
      iWillComeNow: false, // 在离座提醒页的点击
      iTakePic: false, // 拍照留存
      iWillCome: false,//我回来了
      icome_name: null, //我回来了那个人的名字
      icome_alerm: '00:00', // 我回来了后计时器停止的时间
      iBell: false, // 计时器
      iBell_alerm: '00:00', // 计时器时间,
      t: null, // 计数器
      t1: null, // 请求runSeat计数器
      iComeDone: 0,//用来记录是否清除定时器
      msg: '我要反占座',
      isFan: 0,  //是否是反占座，0为我回来了，1为反占座
      isScan: 0, //是否扫码成功，0为未成功，1为成功
      time: 60,
    });
  },
  todo:function(){
    const that = this;
    wx.request({
      url: 'https://2016.bookgo.com.cn/wxapp/index/todo/user_id/' + that.data.userId,
      data: {},
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log('**********我要疯了****************')
        console.log(res)
        switch (res.data.code) {
          case 101:
            // 没有未完成状态，可直接操作
            console.log('done');
            that.pageControl('pageShow');
            break;
          case 102:
            // 将状态信息更新
            var data = res.data.data;
            that.pageControl('choiceShow');
            if(data.type == 'irecive'){
              // 有接收离座提醒的状态
              that.setData({
                  seat_num:data.seat_num
              });
              that.status_iRecive();
            }else{
              // 有反占座中的状态
              that.runSeat(data.id);
              that.setData({
                seat_num:data.seat_num
              });
              that.status_iFan();
            }
            
            break;
          case 104:
            // 服务器错误
            wx.showModal({
              title: '提示',
              content: res.data.data,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            });
            break;
          default:
            console.log(res.data)
        }
      },
      fail: function (res) {

      },
      complete: function () {

      }
    });
  },
  status_iRecive:function(){
    this.pageControl('choiceShow');
    this.titleControl('iReciveNow');
    this.setData({
      iRecive: false,
      iWillCome: false,
      iWillComeNow: true
    })
  },
  status_iFan:function(){
    this.titleControl('iBell');
    this.setData({
      iRecive: false,
      iTakePic: true,
      iWillCome: false,
    });
  },
  get_rest_time:function(){

  },
  rest_time:function(){
    return false;
    var d = new Date();
    var hour = (d.getHours());
    var minute = d.getMinutes();
    minute = (minute < 10) ? ('0' + minute) : ('' + minute);
    var now = parseInt(hour + '' + minute);
    console.log(now);
    if(now < 1130) return false;
    if(now >= 1130 && now <= 1430) {
      this.rest_alert();
      return true;
    }
    if(1430 < now && now < 1700) return false;
    if(1700 <= now && now <= 1900) {
      this.rest_alert();
      return true;
    }
    if(now > 1900) return false;
  },
  rest_alert:function(){
    wx.showModal({
      title: '提示',
      content: '就餐休息时间段允许保留座位，此期间暂停反占座功能。',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
        }
      }
    });
  },
  post_jubao:function(){
    var seat_num_id = this.data.seat_num_id;
    var userId = this.data.userId;
    var seat_num = this.data.seat_num;
    wx.navigateTo({
      url: '/bookgo/fan/report/report?seat_num_id=' + seat_num_id + '&userid=' + userId + '&seat_num=' + seat_num
    });
  }
  
})
